package com.zdd.chap7news.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@Controller
public class NewsController {
    @Autowired
    private RedisTemplate redisTemplate;

    //访问首页功能
    @RequestMapping("/index")
    public String index(){
        return "index";
    }

    //更新浏览量，获取最新点赞数并在页面中显示
    @RequestMapping("/detail/{id}")
    public String detail(@PathVariable("id")int id, Model model){
        //从redis中读取数据，数据结构式HashSet，以news_+id为键，分别为read字段存储阅读次数，以zan字段存储点赞次数
        Map<String,String> map=redisTemplate.opsForHash().entries("news_"+id);
        //获取阅读量
        String countRead=map.get("read");
        if(countRead==null||countRead.equals("")){
            //如果之前没有阅读过，则阅读次数设置为1
            countRead="1";
        }else{
            //如果阅读过，则阅读次数加1
            countRead=(Integer.parseInt(countRead)+1)+"";
        }
        //更新hashmap
        map.put("read",countRead);
        //将数据更新到redis
        redisTemplate.opsForHash().putAll("news_"+id,map);
        //将数据放入model域，前端就能够显示
        model.addAllAttributes(map);
        String str="news"+id;
        return str;
    }

    //点赞功能
    @RequestMapping("/addZan")
    @ResponseBody
    public String addZan(int id){
        Map<String,String> map=redisTemplate.opsForHash().entries("news_"+id);
        //取出原来的赞数
        String countZan=map.get("zan");
        if(countZan==null||countZan.equals("")){
            //如果没有赞过，则赞数为1
            countZan="1";
        }else{
            //如果以前赞过，则赞数加1
            countZan=(Integer.parseInt(countZan)+1)+"";
        }
        //将最新的赞数保存到redis
        redisTemplate.opsForHash().put("news_"+id,"zan",countZan);
        return countZan;
    }
}
